package com.community.comsys.controller;

import java.util.List;
import java.util.concurrent.TimeUnit;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.community.common.annotation.Log;
import com.community.common.core.controller.BaseController;
import com.community.common.core.domain.AjaxResult;
import com.community.common.enums.BusinessType;
import com.community.comsys.domain.Community;
import com.community.comsys.service.ICommunityService;
import com.community.common.utils.poi.ExcelUtil;
import com.community.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import com.community.common.core.redis.RedisCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 项目管理Controller
 * 
 * @author 潇东
 * @date 2025-10-27
 */
@RestController
@RequestMapping("/comsys/mange")
public class CommunityController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(CommunityController.class);

    @Autowired
    private ICommunityService communityService;

    @Autowired
    private RedisCache redisCache;
    
    // 缓存键前缀
    private static final String CACHE_KEY_PREFIX = "comsys:community:";
    // 缓存过期时间（分钟）
    private static final int CACHE_TIMEOUT = 30;
    /**
     * 统计社区数量
     */
    @GetMapping("/count")
    public AjaxResult count(){
        String cacheKey = CACHE_KEY_PREFIX + "count";
        
        // 尝试从缓存获取
        Integer cachedCount = redisCache.getCacheObject(cacheKey);
        if (cachedCount != null) {
            log.info("✅ 从Redis缓存获取社区数量统计");
            return success(cachedCount);
        }
        
        // 缓存未命中，从数据库查询
        Long count = communityService.count();
        Integer result = count.intValue();
        
        // 缓存查询结果
        redisCache.setCacheObject(cacheKey, result, CACHE_TIMEOUT, TimeUnit.MINUTES);
        log.info("社区数量统计已缓存到Redis");
        
        return success(result);
    }
    
    /**
     * 生成缓存键
     */
    private String generateCacheKey(String operation, Object param) {
        StringBuilder key = new StringBuilder(CACHE_KEY_PREFIX);
        key.append(operation);
        
        if (param != null) {
            // 简单的缓存键生成策略，可以根据实际需求调整
            key.append(":").append(param.toString().hashCode());
        }
        
        return key.toString();
    }
    
    /**
     * 清除所有社区相关缓存
     */
    private void clearCommunityCache() {
        log.info("清除社区相关所有缓存");
        // 获取所有社区相关的缓存键并删除
        redisCache.deleteObject(redisCache.keys(CACHE_KEY_PREFIX + "*"));
    }

    /**
     * 查询项目管理列表
     */
    @PreAuthorize("@ss.hasPermi('comsys:mange:list')")
    @GetMapping("/list")
    public TableDataInfo list(Community community)
    {
        // 生成缓存键，包含查询参数的标识
        String cacheKey = generateCacheKey("list", community);
        log.info("生成的缓存key: {}", cacheKey);
        
        // 尝试从缓存获取
        TableDataInfo cachedResult = redisCache.getCacheObject(cacheKey);
        if (cachedResult != null) {
            log.info("✅ 从Redis缓存获取社区列表数据");
            return cachedResult;
        }
        
        // 缓存未命中，从数据库查询
        startPage();
        List<Community> list = communityService.selectCommunityList(community);
        TableDataInfo result = getDataTable(list);
        
        // 缓存查询结果
        redisCache.setCacheObject(cacheKey, result, CACHE_TIMEOUT, TimeUnit.MINUTES);
        log.info("社区列表数据已缓存到Redis");
        
        return result;
    }

    /**
     * 导出项目管理列表
     */
    @PreAuthorize("@ss.hasPermi('comsys:mange:export')")
    @Log(title = "项目管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Community community)
    {
        List<Community> list = communityService.selectCommunityList(community);
        ExcelUtil<Community> util = new ExcelUtil<Community>(Community.class);
        util.exportExcel(response, list, "项目管理数据");
    }


    @PreAuthorize("@ss.hasPermi('comsys:mange:import')")
    @Log(title = "社区管理", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    public AjaxResult importData(@RequestParam("file") MultipartFile file){
        try {
            ExcelUtil<Community> util = new ExcelUtil<>(Community.class);
            // 通过ExcelUtil工具类解析上传的Excel文件，将文件内容转换为Community对象列表
            List<Community> communityList = util.importExcel(file.getInputStream());
            // 处理导入的数据
            int result = communityService.importCommunityList(communityList);
            
            if (result > 0) {
                // 导入成功，清除所有缓存
                clearCommunityCache();
            }
            
            return success(result);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取项目管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('comsys:mange:query')")
    @GetMapping(value = "/{communityId}")
    public AjaxResult getInfo(@PathVariable("communityId") Long communityId)
    {
        String cacheKey = CACHE_KEY_PREFIX + "info:" + communityId;
        
        // 尝试从缓存获取
        Community cachedCommunity = redisCache.getCacheObject(cacheKey);
        if (cachedCommunity != null) {
            log.info("✅ 从Redis缓存获取社区详情数据，ID: {}", communityId);
            return success(cachedCommunity);
        }
        
        // 缓存未命中，从数据库查询
        Community community = communityService.selectCommunityByCommunityId(communityId);
        
        // 缓存查询结果
        if (community != null) {
            redisCache.setCacheObject(cacheKey, community, CACHE_TIMEOUT, TimeUnit.MINUTES);
            log.info("社区详情数据已缓存到Redis，ID: {}", communityId);
        }
        
        return success(community);
    }


    /**
     * 新增项目管理
     */
    @PreAuthorize("@ss.hasPermi('comsys:mange:add')")
    @Log(title = "项目管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Community community)
    {
        int result = communityService.insertCommunity(community);
        if (result > 0) {
            // 新增成功，清除所有缓存
            clearCommunityCache();
        }
        return toAjax(result);
    }

    /**
     * 修改项目管理
     */
    @PreAuthorize("@ss.hasPermi('comsys:mange:edit')")
    @Log(title = "项目管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Community community)
    {
        int result = communityService.updateCommunity(community);
        if (result > 0) {
            // 检查是否修改了社区名称
            if (community.getName() != null) {
                log.info("社区名称已修改，需要清除所有相关缓存");
                
                // 清除社区相关缓存
                clearCommunityCache();
                
                // 清除所有关联的实体缓存
                // 清除楼宇缓存
                redisCache.deleteObject(redisCache.keys("comsys:building:*"));
                log.info("已清除所有楼宇相关缓存");
                
                // 清除房屋缓存
                redisCache.deleteObject(redisCache.keys("comsys:house:*"));
                log.info("已清除所有房屋相关缓存");
                
                // 清除商铺缓存
                redisCache.deleteObject(redisCache.keys("comsys:shop:*"));
                log.info("已清除所有商铺相关缓存");
                
                // 清除车位缓存
                redisCache.deleteObject(redisCache.keys("comsys:parking:space:*"));
                log.info("已清除所有车位相关缓存");
                
                // 清除储物间缓存
                redisCache.deleteObject(redisCache.keys("comsys:storage:room:*"));
                log.info("已清除所有储物间相关缓存");
            } else {
                // 没有修改名称，只清除社区相关缓存
                clearCommunityCache();
            }
            
            // 也可以只清除特定社区的缓存
            if (community.getCommunityId() != null) {
                String specificCacheKey = CACHE_KEY_PREFIX + "info:" + community.getCommunityId();
                redisCache.deleteObject(specificCacheKey);
                log.info("已清除特定社区缓存，ID: {}", community.getCommunityId());
            }
        }
        return toAjax(result);
    }

    /**
     * 删除项目管理
     */
    @PreAuthorize("@ss.hasPermi('comsys:mange:remove')")
    @Log(title = "项目管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{communityIds}")
    public AjaxResult remove(@PathVariable Long[] communityIds)
    {
        int result = communityService.deleteCommunityByCommunityIds(communityIds);
        if (result > 0) {
            // 删除成功，清除所有缓存
            clearCommunityCache();
            
            // 也可以清除特定社区的缓存
            for (Long communityId : communityIds) {
                String specificCacheKey = CACHE_KEY_PREFIX + "info:" + communityId;
                redisCache.deleteObject(specificCacheKey);
                log.info("已清除特定社区缓存，ID: {}", communityId);
            }
        }
        return toAjax(result);
    }


}
